package org.migrantalks.base;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;


/**
 * 统一响应结果封装
 */
public class Result<T> {

    private int code;
    private String msg;
    private T data;
    private boolean success;

    public Result setCode(ResultCode resultCode) {
        this.code = resultCode.code();
        return this;
    }

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public Result setMsg(String msg) {
        this.msg = msg;
        return this;
    }

    public T getData() {
        return data;
    }

    public Result setData(T data) {
        this.data = data;
        return this;
    }

    public boolean isSuccess() {
        return success;
    }

    public Result setSuccess(boolean success) {
        this.success = success;
        return this;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }

    private static final String DEFAULT_SUCCESS_MESSAGE = "操作成功";

    public static Result success(String message) {
        return new Result()
                .setCode(ResultCode.SUCCESS)
                .setMsg(StringUtils.isNoneBlank(message) ? message : DEFAULT_SUCCESS_MESSAGE)
                .setSuccess(true);
    }

    public static <T> Result<T> success(T data) {
        return new Result()
                .setCode(ResultCode.SUCCESS)
                .setMsg(DEFAULT_SUCCESS_MESSAGE)
                .setData(data)
                .setSuccess(true);
    }

    public static <T> Result<T> success(String message, T data) {
        return new Result()
                .setCode(ResultCode.SUCCESS)
                .setMsg(message)
                .setData(data)
                .setSuccess(true);
    }

    public static Result fail(String message) {
        return new Result()
                .setCode(ResultCode.FAIL)
                .setMsg(message)
                .setSuccess(false);
    }

    public static Result fail(ResultCode code, String message) {
        return new Result()
                .setCode(code)
                .setMsg(message)
                .setSuccess(false);
    }
}
